package top.lyjwn.todo.weinxin.applet.component;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.lyjwn.todo.common.redis.RedisMap;
import top.lyjwn.todo.weinxin.api.applet.AuthGetAccessToken;
import top.lyjwn.todo.weinxin.applet.AppletAccessToken;
import top.lyjwn.todo.weinxin.param.WXAppletParam;

import java.util.Date;

@Component
public class AppletAccessTokenHandle {

    private final String REDIS_KEY = "applet:accessToken:";

    @Autowired
    private RedisMap redisMap;

    @Autowired
    private WXAppletParam wxAppletParam;

    @Autowired
    private AuthGetAccessToken authGetAccessToken;

    public boolean save(String jsonstring) {
        AppletAccessToken accessToken = AppletAccessToken.builder(JSONObject.parseObject(jsonstring));
        accessToken.setAcquisitionTime(new Date());
        if ("".equals(accessToken.getErrcode()) || accessToken.getErrcode() == null) {
            this.save(accessToken);
            return true;
        }
        return false;

    }

    public void save(AppletAccessToken accessToken) {
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(accessToken));
        redisMap.set(REDIS_KEY + wxAppletParam.getAppid(), jsonObject, (accessToken.getExpires_in() - 120) * 1000);
    }

    public boolean refresh() {
        String accessTokenJson = authGetAccessToken.getResultString();
        return save(accessTokenJson);
    }

    public AppletAccessToken getAccessToken() {
        JSONObject jsonObject = redisMap.get(REDIS_KEY + wxAppletParam.getAppid());
        return jsonObject != null ? jsonObject.toJavaObject(AppletAccessToken.class) : null;
    }
}
